#include "server.h"
#include "queue.h"

int segPath(char* toPath, Queue* queue){
    char rePath[1024] = {0};
    strcpy(rePath, toPath);
    char* seg = strtok(rePath, "/");
    rearInsert(queue, seg);
    while((seg = strtok(NULL, "/")) != NULL){
        rearInsert(queue, seg);
    }
    return 0;
}

int prin(Stack *path)
{
    node_t *pNode = path->front;
    while (pNode != NULL)
    {
        printf("%s/", pNode->data);
        pNode = pNode->next;
    }
    printf("\n");
    return 0;
}

int cd(char* toPath, char* nowPath, MYSQL* mysql){
    //分离路径
    Queue* segedToPath = createQueue();
    Queue* segedNowPath = createQueue();
    segPath(toPath, segedToPath); //分离前往路径
    segPath(nowPath, segedNowPath); //分离目前路径

    while(segedToPath->size > 0){
        if(strcmp(segedToPath->front->data, ".") == 0){
            frontQueuePop(segedToPath);
        }else if(strcmp(segedToPath->front->data, "..") == 0){
            frontQueuePop(segedToPath);
            rearQueuePop(segedNowPath);
            if(segedNowPath->size < 2){
                printf("路径错误：返回到了根目录上级!\n");
                return -1;
            }
        }else if(strcmp(segedToPath->front->data, "~") == 0){
            frontQueuePop(segedToPath);
            while(segedNowPath->size > 2){
                rearQueuePop(segedNowPath);
            }
        }else{
            char *tmp = frontQueuePop(segedToPath);
            rearInsert(segedNowPath, tmp);
        }
    }
    char path[1024] = {0};
    while(segedNowPath->size > 0){
        strcat(path, frontQueuePop(segedNowPath));
        if(segedNowPath->size != 0){
            strcat(path, "/");
        }
    }

    //判断是否存在用户要访问的目录
    printf("path = %s\n", path);
    char sql[1024] = "select file.path from file where path = '";
    sprintf(sql, "%s%s' and type = 'd' and tomb = '0';", sql, path);
    //printf("sql = %s\n", sql);
    int qret = mysql_query(mysql, sql);
    //printf("qret = %d\n", qret);
    MYSQL_RES* res = mysql_store_result(mysql);
    MYSQL_ROW row = mysql_fetch_row(res);
    //printf("row[0] = %s\n", row[0]);
    if(mysql_num_rows(res) == 0){
        printf("路径错误：不存在该目录!\n");
        return -1;
    }else{  //存在用户要前往的目录，修改全局路径变量
        bzero(nowPath, sizeof(nowPath));
        strcpy(nowPath, path);  //修改全局路径变量
        printf("用户目前路径：%s\n", nowPath);
    }
    mysql_free_result(res);

    return 0;
}
    



